<?php


namespace App\Models\CacheModel\zl1_relation;


use App\Models\Api\BaseCache;
use think\Cache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl1AstrCommunityArticle extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl1_astr_community_article';

    protected $cacheModel = 'astr_community.article';

    /**
     * 发布星座讨论
     * @param array $data
     * @return int|string
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)
                ->setCacheKeyDetail('user_list', $data['uid'])
                ->listAdd([$id => $id], 0, 'user_list');
        }
        catch (\Exception $e)
        {
            Log::write('Zl1AstrCommunityArticle model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            $id = 0;
        }

        return $id;
    }

    /**
     * 更新星座讨论详情
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            // 更新数据
            $this->where(['id' => $id])->update($data);
            // 更新缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl1AstrCommunityArticle model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }
    }

    /**
     * 获取 用户发布的星座讨论IDs
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getUserArticleIds(int $uid, int $page, int $limit = 10): array
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('user_list', $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'status' => 0])->order('id ' . $sortType)->column('id');
                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0, 'user_list');

        return $resData;
    }

    /**
     * 获取星座讨论IDS
     * @param array $inSigns
     * @param array $relationIds
     * @return array
     */
    public function getArticleIds(array $inSigns, array $relationIds)
    {
        try
        {
            $where = ['is_hide' => 0, 'status' => 0];
            if (empty($inSigns) && $relationIds)
            {   // 搜索关系
                $where['relation_id'] = ['in', $relationIds];
            } elseif ($inSigns && empty($relationIds))
            {   // 搜索星座
                $where['in_sign'] = ['in', $inSigns];
            } elseif ($inSigns && $relationIds)
            {   // 搜索 星座 + 关系
                $inSignRelationIds = [];
                foreach ($inSigns as $inSignItem)
                {
                    foreach ($relationIds as $relationIdItem)
                    {
                        $inSignRelationIds[] = $inSignItem * 10000 + $relationIdItem;
                    }
                }

                $where['in_sign_relation_id'] = ['in', $inSignRelationIds];
            }

            $resIds = $this->where($where)->order('id desc')->field('id')->paginate()->toArray();
        }
        catch (\Exception $e)
        {
            Log::write('Zl1AstrCommunityArticle model => getArticleIds()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return [];
        }

        return $resIds;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $where = ['id' => ['in', $ids]];
        $field = 'is_hide,status,uid,title,photos,in_sign,relation_id,read_num,comment_num,zan_num,zan_num2,extend,create_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $orderItemData)
        {
            $resData[$orderId] = arrayKeyData2int($orderItemData, ['id', 'is_hide', 'uid', 'status', 'in_sign', 'relation_id', 'read_num', 'comment_num', 'zan_num', 'zan_num2', 'create_time']);

            if (isset($orderItemData['photos']))
            {
                $resData[$orderId]['photos'] = json_decode($orderItemData['photos'], true);
            }

            if (isset($orderItemData['extend']))
            {
                $resData[$orderId]['extend'] = $orderItemData['extend'] ? json_decode($orderItemData['extend'], true) : [];
            }
        }

        return $resData;
    }

    /**
     * 更新 星座讨论 相关信息
     * @param array $articleInfo 问答问题信息
     *      [   问题信息内 需包含字段
     *          'id'    问题ID
     *          'read_num'  已读数 新增前
     *          'comment_num'  评论数 新增前
     *      ]
     * @param int $changeType 更新类型 1=>已读数 2=>评论数
     * @param int $inc 新增数
     * @throws \Exception
     */
    public function changeArticleInfo(array $articleInfo, int $changeType, int $inc = 1): void
    {
        $cacheKey = 'astr_community_article:change_num:' . $articleInfo['id'];

        $num = Cache::inc($cacheKey);
        $changeTypeCacheKey = [
            1 => 'read_num',
            2 => 'comment_num',
        ];
        // 更新缓存
        $articleInfo[$changeTypeCacheKey[$changeType]] = $articleInfo[$changeTypeCacheKey[$changeType]] + $inc;
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $articleInfo['id'])->setCache([$changeTypeCacheKey[$changeType] => $articleInfo[$changeTypeCacheKey[$changeType]]]);

        $updateStep = 1;    //更新数据库 频率
        if ($num >= $updateStep)
        {
            $this->where(['id' => $articleInfo['id']])->update([
                'read_num' => $articleInfo['read_num'],
                'comment_num' => $articleInfo['comment_num'],
            ]);

            Cache::set($cacheKey, 0, 604800); //7天有效期
        }
    }

    /**
     * 获取今日 热点 星座讨论 ID
     * @param int $time 当前时间时间戳
     * @return array
     */
    public function getHotArticleByToday(int $time): array
    {
        $time = $time - 604800; // 获取7天前的时间
        // 当前缓存以缓存的有效期 来控制 缓存更新频率 缓存过期时间越短 更新频率越快
        $resData = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheTime(86400)   // 缓存1天过期 获取时间的七天以内
            ->getDataAndSet(function () use ($time)
            {
                try
                {
                    $data = $this->where(['status' => 0, 'is_hide' => 0, 'create_time' => ['>=', $time]])->column('in_sign,read_num,comment_num', 'id');

                    $resData = [];
                    $hotData = [
                        1 => 0,
                        2 => 0,
                        3 => 0,
                        4 => 0,
                        5 => 0,
                        6 => 0,
                        7 => 0,
                        8 => 0,
                        9 => 0,
                        10 => 0,
                        11 => 0,
                        12 => 0,
                    ];
                    foreach ($data as $id => $item)
                    {
                        $hotNum = $item['read_num'] + $item['comment_num'];
                        if ($hotNum > $hotData[$item['in_sign']] || !isset($resData[$item['in_sign']]))
                        {
                            $hotData[$item['in_sign']] = $hotNum;
                            $resData[$item['in_sign']] = $id;
                        }
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    Log::write('Zl1AstrCommunityArticle model => getHotArticleByToday()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

                    return [];
                }
            }, [], 'today_hot');

        return $resData;
    }

}
